//
//  SwiftyJSON+IJSONInitializer.swift
//  PMS
//
//  Created by 何海涛 on 2016/12/27.
//  Copyright © 2016年 途家. All rights reserved.
//

import Foundation

public protocol IJSONInitializer {
    
    init(json: JSON)
}

// auto empty properties.
extension IJSONInitializer {
    
    static public func empty() -> Self {
        return Self.init(json: JSON.null)
    }
}

// for normal entity constructor.
extension JSON {
    
    public func toEntity<T: IJSONInitializer>() -> T {
        return T.init(json: self)
    }
    
    public func toNullableEntity<T: IJSONInitializer>() -> T? {
        return self == JSON.null ? nil : T.init(json: self)
    }
    
    public func toEntityList<T: IJSONInitializer>() -> [T] {
        return self.arrayValue.map({ $0.toEntity() })
    }
    
    public func toNullableEntityList<T: IJSONInitializer>() -> [T]? {
        return self == JSON.null ? nil : self.toEntityList()
    }
    
    public func toEntityDictionary<T: IJSONInitializer>() -> [String: T] {
        var result: [String: T] = [:]
        for (key, value) in self.dictionaryValue {
            result[key] = T.init(json: value)
        }
        return result
    }
    
    public func toNullableEntityDictionary<T: IJSONInitializer>() -> [String: T]? {
        return self == JSON.null ? nil : self.toEntityDictionary()
    }
}

// for ISerializeCopyableProtocol's value copy
extension JSON {
    
    public func copyValueIfNotNull(_ member: String, copyAction: (_ val: JSON)->Void) {
        let val = self[member]
        if val != JSON.null {
            copyAction(val)
        }
    }
}
